package com.example.onlinemonitoring.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.onlinemonitoring.model.common.*;
import com.example.onlinemonitoring.query.QueryObject;
import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.autoRun.ComRunner;
import com.example.onlinemonitoring.comCenter.AscCom;
import com.example.onlinemonitoring.model.*;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import tk.mybatis.mapper.entity.Example;

import com.example.onlinemonitoring.serviceImpl.AppdeviceServiceImpl;
import com.example.onlinemonitoring.serviceImpl.AscsensorServiceImpl;

/**
 * Controller
 * 该部分代码为自动生成，请勿随意修改
 * 如有改动请删除该注释
 * 
 * @author little pig page
 * @date 2022-04-11
 */
@Api(value = "消弧控制器设备", tags = { "消弧控制器设备接口" })
@RestController
@RequestMapping("/arcSuppressionController")
public class AscsensorController {
    Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
    @Autowired
    AscsensorServiceImpl ascserviceimpl;
    @Autowired
    AppdeviceServiceImpl appdeviceimpl;

    @ApiOperation(value = "修改设备参数", notes = "修改设备参数")
    @ResponseBody
    @RequestMapping(value = "/updateAll", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public MyResult<Integer> updateAll(@RequestBody String jsonParam,
            @RequestParam(value = "stationid", required = false) Integer stationid,
            @RequestParam(value = "deviceaddr", required = false) Integer deviceaddr,
            @RequestParam(value = "devicegroup", required = false) Integer devicegroup) {
        JSONObject object = JSONObject.parseObject(jsonParam);
        Ascsensor record = object.toJavaObject(Ascsensor.class);
        MyResult<Integer> m = new MyResult<Integer>();
        record.setStationid(stationid);
        record.setDevicegroup(devicegroup);
        record.setDeviceaddr(deviceaddr);
        if (ascserviceimpl.Update(record, false) >= 1) {
            m.setMsg("修改成功");
            m.setCode(0);
        } else {
            m.setMsg("修改失败");
            m.setCode(1);
        }
        return m;
    }

    @ApiOperation(value = "修改设备报警", notes = "修改设备报警")
    @ResponseBody
    @RequestMapping(value = "/updateAlarm", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public MyResult<Integer> updateAlarm(@RequestBody String jsonParam,
            @RequestParam(value = "stationid", required = false) Integer stationid,
            @RequestParam(value = "deviceaddr", required = false) Integer deviceaddr,
            @RequestParam(value = "devicegroup", required = false) Integer devicegroup) {
        JSONObject object = JSONObject.parseObject(jsonParam);
        MyResult<Integer> m = new MyResult<Integer>();
        Ascsensor record = new Ascsensor();
        record.setStationid(stationid);
        record.setDevicegroup(devicegroup);
        record.setDeviceaddr(deviceaddr);
        if (ascserviceimpl.Update(record, false) >= 1) {
            m.setMsg("修改成功");
            m.setCode(0);
        } else {
            m.setMsg("修改失败");
            m.setCode(1);
        }
        return m;
    }

    @ApiOperation(value = "查询实时表数据", notes = "查询实时表数据")
    @ResponseBody
    @GetMapping("/selectSensorData")
    public MyResult<Ascsensor> selectSensorData(
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "limit", required = false) Integer limit,
            @RequestParam(value = "stationid", required = false) Integer stationid,
            @RequestParam(value = "deviceaddr", required = false) Integer deviceaddr,
            @RequestParam(value = "devicegroup", required = false) Integer devicegroup) {
        Ascsensor record = new Ascsensor();
        record.setStationid(stationid);
        record.setDeviceaddr(deviceaddr);
        record.setDevicegroup(devicegroup);
        QueryObject qo = new QueryObject(page, limit);
        return ascserviceimpl.getList(record, qo);
    }

    @ApiOperation(value = "修改监测点名称", notes = "修改监测点名称")
    @ResponseBody
    @RequestMapping(value = "/updateMonitorName", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public MyResult<Integer> updateMonitorName(@RequestBody String jsonParam,
            @RequestParam(value = "id", required = false) Long id) {
        JSONObject object = JSONObject.parseObject(jsonParam);
        MyResult<Integer> m = new MyResult<Integer>();
        Ascsensor record = new Ascsensor();
        record.setId(id);
        record.setPointname(object.getString("pointname"));
        if (ascserviceimpl.Update(record, true) >= 1) {
            m.setMsg("修改成功");
            m.setCode(0);
        } else {
            m.setMsg("修改失败");
            m.setCode(1);
        }
        return m;
    }

    @ApiOperation(value = "查询历史表数据", notes = "查询历史表数据")
    @ResponseBody
    @GetMapping("/selectHistoryData")
    public MyResult<Aschistory> selectHistoryData(
            @RequestParam(value = "page", required = true) Integer page,
            @RequestParam(value = "limit", required = true) Integer limit,
            @RequestParam(value = "stationid", required = false) Integer stationid,
            @RequestParam(value = "deviceaddr", required = false) Integer deviceaddr,
            @RequestParam(value = "devicegroup", required = false) Integer devicegroup,
            @RequestParam(value = "start", required = false) String begintime,
            @RequestParam(value = "end", required = false) String endtime,
            @RequestParam(value = "pagecount", required = false) Integer pagecount) {
        Aschistory record = new Aschistory();
        record.setStationid(stationid);
        record.setDeviceaddr(deviceaddr);
        record.setDevicegroup(devicegroup);
        pagebase pagebase = new pagebase();
        pagebase.setBegintime(begintime);
        pagebase.setEndtime(endtime);
        pagebase.setPage(page);
        pagebase.setLimit(limit);
        pagebase.setPagecount(pagecount);
        return ascserviceimpl.getHisList(record, pagebase);
    }

    @ApiOperation(value = "查询历史表曲线", notes = "查询历史表曲线")
    @ResponseBody
    @GetMapping("/selectHistoryCurve")
    public MyResult<chartres> selectHistoryCurve(
            @RequestParam(value = "page", required = true) Integer page,
            @RequestParam(value = "limit", required = true) Integer limit,
            @RequestParam(value = "stationid", required = false) Integer stationid,
            @RequestParam(value = "deviceaddr", required = false) Integer deviceaddr,
            @RequestParam(value = "devicegroup", required = false) Integer devicegroup,
            @RequestParam(value = "start", required = false) String begintime,
            @RequestParam(value = "end", required = false) String endtime,
            @RequestParam(value = "pagecount", required = false) Integer pagecount,
            @RequestParam(value = "lstr", required = false) String lstr) {

        Aschistory record = new Aschistory();
        record.setStationid(stationid);
        record.setDeviceaddr(deviceaddr);
        record.setDevicegroup(devicegroup);
        pagebase pagebase = new pagebase();
        pagebase.setBegintime(begintime);
        pagebase.setEndtime(endtime);
        pagebase.setPage((page - 1) * limit);
        pagebase.setLimit(limit);
        pagebase.setIsasc(true);
        pagebase.setPagecount(pagecount);
        return ascserviceimpl.getHisCurveList(record, lstr, pagebase);
    }

    @ApiOperation(value = "消弧控制器控制", notes = "消弧控制器控制")
    @ResponseBody
    @GetMapping("/cmdDevice")
    public MyResult<String> cmdDevice(
            @RequestParam(value = "stationid", required = true) Integer stationid,
            @RequestParam(value = "devicegroup", required = true) Integer devicegroup,
            @RequestParam(value = "deviceaddr", required = true) Integer deviceaddr,
            @RequestParam(value = "cmd", required = true) Integer cmd) {
        Appdevice record = new Appdevice();
        Example example = new Example(Appdevice.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("stationid", stationid);
        criteria.andEqualTo("devicegroup", devicegroup);
        criteria.andEqualTo("simple", "asc");
        record = appdeviceimpl.selectOneByExample(example);
        int index = 0;
        AscCom oc = null;
        switch (record.getCommunicationmode()) {
            case 1:
                index = CommPortManager.strGetNum(record.getCom());
                oc = (AscCom) ComRunner.devmap.get(index);
                break;
            case 2:
                index = record.getId();
                oc = (AscCom) ComRunner.netmap.get(index);
                break;
            case 3:
                index = record.getId();
                oc = (AscCom) ComRunner.netservermap.get(index);
                break;
            default:
                break;
        }
        if (oc == null) {
            return new MyResult<String>(1, "未开启！");
        }
        MyResult<String> res = new MyResult<>();
        // 每次发送控制之前就清空返回
        oc.setControllerRet("");
        String cstr = "";
        cstr = String.format("%02X", deviceaddr) + "05000" + cmd + "FF00";
        oc.ControlCommand(cstr);
        if (!oc.getControllerRet().equals("")) {
            List<String> l = new ArrayList<String>();
            l.add(oc.getControllerRet());
            res.setData(l);
            res.setCode(0);
            res.setMsg("操作成功！");
            return res;
        }
        res.setCode(1);
        res.setMsg("操作失败！");
        return res;
    }

    /**
     * 导出Excel
     */
    @GetMapping("exportToExcel")
    public void exportToExcel(HttpServletResponse response,
            @RequestParam(value = "stationid", required = true) Integer stationid,
            @RequestParam(value = "devicegroup", required = true) Integer devicegroup,
            @RequestParam(value = "deviceaddr", required = true) Integer deviceaddr,
            @RequestParam(value = "start", required = false) String begintime,
            @RequestParam(value = "end", required = false) String endtime) throws IOException {
        Aschistory record = new Aschistory();
        record.setStationid(stationid);
        record.setDeviceaddr(deviceaddr);
        record.setDevicegroup(devicegroup);
        pagebase pagebase = new pagebase();
        pagebase.setBegintime(begintime);
        pagebase.setEndtime(endtime);
        Workbook wb = ascserviceimpl.writeToExcelByList(record, pagebase);
        OutputStream output = response.getOutputStream();
        String fileName = "data.xlsx";
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition",
                "attachment;filename=" + fileName + ";" + "filename*=utf-8''" + fileName);
        wb.write(output);
        output.close();
    }

    /**
     * 导出Excel
     */
    @GetMapping("exportToSensorExcel")
    public void exportToSensorExcel(HttpServletResponse response,
            @RequestParam(value = "stationid", required = false) Integer stationid,
            @RequestParam(value = "devicegroup", required = false) Integer devicegroup,
            @RequestParam(value = "deviceaddr", required = false) Integer deviceaddr) throws IOException {
        Ascsensor record = new Ascsensor();
        record.setStationid(stationid);
        record.setDeviceaddr(deviceaddr);
        record.setDevicegroup(devicegroup);
        Workbook wb = ascserviceimpl.writeToExcelBySensorList(record);
        OutputStream output = response.getOutputStream();
        String fileName = "data.xlsx";
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition",
                "attachment;filename=" + fileName + ";" + "filename*=utf-8''" + fileName);
        wb.write(output);
        output.close();
    }
}
